import { asyncRoutes, constantRoutes } from '@/router';

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permission, route) {
  if (route.meta && route.meta.permission) {
    if (permission === undefined) {
      return false;
    }
    let flag = false;
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i]);
      if (flag) {
        return true;
      }
    }
    return false;
  }
  return true;
}

function filterAsyncRouter(routerMap, role) {
  const accessedRouters = routerMap.filter(route => {
    if (hasPermission(role, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, role);
      }
      return true;
    }
    return false;
  });
  return accessedRouters;
}

const state = {
  routers: constantRoutes,
  addRouters: []
};

const mutations = {
  SET_ROUTERS: (state, routers) => {
    state.addRouters = routers;
    state.routers = constantRoutes.concat(routers);
  }
};

const actions = {
  GenerateRoutes({ commit }, data) {
    return new Promise(resolve => {
      /* const { roles } = data;
      const routerMap = cloneDeep(asyncRouterMap);
      const accessedRouters = filterAsyncRouter(routerMap, roles);
      commit('SET_ROUTERS', accessedRouters);
      resolve(); */
      const { roles } = data;
      let accessedRoutes;
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || [];
      } else {
        accessedRoutes = filterAsyncRouter(asyncRoutes, roles);
      }
      commit('SET_ROUTERS', accessedRoutes);
      resolve(accessedRoutes);
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
